Day 39 UnderBar_Part2 (Intersection)

๐Ÿ˜ญ์•„์ง ๊ฒฐ๋ก ์ด ๋‚˜์ง€ ์•Š์€ Intersection

ํ’€์ด๋ฒ•์„ ์ดํ•ดํ•˜๊ณ  ๋„˜์–ด๊ฐ€๊ณ  ์‹ถ์ง€๋งŒ, ๋‚ด๊ฐ€ ํ‘ธ๋Š” ๋ฐฉ์‹์—์„œ ์ž‘๋™์ด ๋˜๊ฒŒ ๋งŒ๋“œ๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๊ณ  ์‹ถ์—ˆ๋‹ค. (์‚ฌ์‹ค ํ’€์ด๋ฒ•์ด ์ดํ•ด๊ฐ€ ๋˜์ง€ ์•Š์•„์„œ ์ด๊ธฐ๋„ ํ•˜๋‹ค.)

์ฝ”๋“œ๋ฅผ ๋ธ”๋กœ๊ทธ์— ์˜ฌ๋ฆฌ๋Š” ๊ฒƒ์€ ๊ฐ€๊ธ‰์  ์ง€์–‘ํ•˜๊ณ  ์‹ถ์ง€๋งŒ ๋‚˜๋Š” ๊ทธ๋ ‡๊ฒŒ ์ƒ๊ฐํ•œ๋‹ค.

์ด ์ฝ”๋“œ๋ฅผ ๋ฒ ๊ปด ๋ณต๋ถ™ํ•ด ๋„ฃ์–ด ํ†ต๊ณผํ•ด์„œ ๋Œ€ํ†ต๋ น ํ‘œ์ฐฝ์žฅ ๋ฐ›๋Š” ๊ฑฐ ์•„๋‹ˆ์ง€ ์•Š๋Š”๊ฐ€ ์‹ถ๋‹ค. ์ฝ”๋“œ ๋ฒ ๊ปด ๋„ฃ์–ด์„œ ํ†ต๊ณผ๋˜์—ˆ๋‹ค๊ณ  ๊ทธ๊ฒŒ ์ž๊ธฐ๊บผ ๋˜๋Š” ๊ฑด ์•„๋‹ํ…Œ๋‹ˆ ๋ณธ์ธ์ด ๋” ์ž˜ ์•Œ๊ฒ ์ง€ ์‹ถ๋‹ค.

์—ฌํŠผ ๊ฐ์„คํ•˜๊ณ  ์–ธ๋”๋ฐ” _.intersection ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—ญํ• ์„ ํ•˜๊ณ  ์žˆ๋‹ค.

_.intersection์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐฐ์—ด์„ ์ž…๋ ฅ๋ฐ›์•„, ๊ต์ง‘ํ•ฉ ๋ฐฐ์—ด์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
๊ต์ง‘ํ•ฉ ๋ฐฐ์—ด์€ ๋ชจ๋“  ๋ฐฐ์—ด์— ๊ณตํ†ต์œผ๋กœ ๋“ฑ์žฅํ•˜๋Š” ์š”์†Œ๋“ค๋งŒ์„ ์š”์†Œ๋กœ ๊ฐ–๋Š” ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
๊ต์ง‘ํ•ฉ ๋ฐฐ์—ด์˜ ์š”์†Œ๋“ค์€ ์ฒซ ๋ฒˆ์งธ ์ž…๋ ฅ์ธ ๋ฐฐ์—ด์„ ๊ธฐ์ค€์œผ๋กœ ํ•ฉ๋‹ˆ๋‹ค.
๊ต์ง‘ํ•ฉ์ด ์—†๋Š” ๊ฒฝ์šฐ ๋นˆ ๋ฐฐ์—ด์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
์•„๋ž˜ ์˜ˆ์ œ๋ฅผ ์ฐธ๊ณ ํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.
const set1 = ['a', 'e', 'b', 'c'];
const set2 = ['c', 'd', 'e'];
const result = _.intersection(set1, set2);
console.log(result) // --> ['e', 'c']
// ์ฒซ ๋ฒˆ์งธ ๋ฐฐ์—ด์— 'e'๊ฐ€ ๋จผ์ € ๋“ฑ์žฅ

๐Ÿ‘น๋‚˜์˜ ๋ฌธ์ œ ํ’€์ด๋ฒ•

_.intersection = function(...arrays) {
  let lumpOfArrays = []
  let arrNum = arrays.length
  console.log(arrNum)
  _.each(arrays, function(arr) {
    lumpOfArrays.push(...arr)
  })
  let transObj = {}
  for (let i = 0; i < lumpOfArrays.length; i++) {
    if (!_.includes(Object.keys(transObj), lumpOfArrays[i])) {
      transObj[lumpOfArrays[i]] = 1
    } else {
      transObj[lumpOfArrays[i]] = transObj[lumpOfArrays[i]] + 1
    }
  }
  let result = []
  for (let key in transObj) {
    if (transObj[key] === arrNum) {
      result.push(key)
    }
  }
  return result
}

๋งˆ์ง€๋ง‰ ์ผ€์ด์Šค๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” ํ†ต๊ณผ๊ฐ€ ๋œ๋‹ค, ๋งˆ์ง€๋ง‰ ์ผ€์ด์Šค๋ฅผ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜๋Š” ์ด์œ ๋Š” Object.keys(transObj) ์—ฌ๊ธฐ์— ๋“ค์–ด๊ฐ€๋Š” ์ฆ‰, ๊ฐ์ฒด์— ๋“ค์–ด๊ฐ€๋Š” ํ‚ค๋Š” ๋ชจ๋‘ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜๋˜๊ธฐ ๋•Œ๋ฌธ์ธ๋“ฏ ์‹ถ๋‹ค. ๊ทธ๋ž˜์„œ ์ˆซ์ž๋„ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๋€Œ์–ด ํ‚ค๊ฐ€ ๋“ค์–ด๊ฐ€๋Š”๋ฐ, ํ—ฌํ”„๋ฐ์Šคํฌ์— ์ข€์ „ ๋‹ต๋ณ€์„ ๋ฐ›์€ ์ƒํ™ฉ์—์„œ ๋‚ด์ผ ๋‹ค์‹œ ํŠธ๋ผ์ด ํ•ด๋ณด๋ ค ํ•œ๋‹ค.


Written by@[DotoriMook]
ํ”„๋ก ํŠธ์—”๋“œ ์ฃผ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž ๋„ํ† ๋ฆฌ๋ฌต์˜ ๊ธฐ์ˆ ๊ฐœ๋ฐœ ๋ธ”๋กœ๊ทธ ์ž…๋‹ˆ๋‹ค.

GitHubMediumTwitterFacebook